<template>
  <div ref="chartContainer" class="chart"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { fetchCategoryProductCount } from '@/api/data';

const chartContainer = ref(null);
let chartInstance = null;

const option = {
  title: {
    text: '各类目商品数量统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 30,
      interval: 0 // 强制显示所有标签
    }
  },
  yAxis: {
    type: 'value',
    name: '商品数量',
    axisLine: {
      show: true
    },
    axisTick: {
      show: true
    }
  },
  series: [
    {
      name: '商品数量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#5470c6',
        borderRadius: [4, 4, 0, 0] // 顶部圆角
      },
      barWidth: '60%',
      label: {
        show: true,
        position: 'top'
      }
    }
  ]
};

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    
    // 响应式调整
    const resizeObserver = new ResizeObserver(() => {
      chartInstance?.resize();
    });
    resizeObserver.observe(chartContainer.value);
    
    // 组件卸载时清理
    onBeforeUnmount(() => {
      resizeObserver.disconnect();
      chartInstance?.dispose();
    });
  }
};

// 加载数据
const loadData = async () => {
  const data = await fetchCategoryProductCount();
  option.xAxis.data = data.map(item => item.categoryName);
  option.series[0].data = data.map(item => item.productCount);
  
  if (chartInstance) {
    chartInstance.setOption(option);
  }
};

onMounted(() => {
  initChart();
  loadData();
});
</script>

<style scoped>
.chart {
  height: 100%;
  width: 100%;
  min-height: 400px; /* 确保足够高度显示完整图表 */
}
</style>